package com.example.service;

import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Address;
import com.example.mapper.AddressMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 地址服务业务处理层
 */
@Service
public class AddressService {

    @Resource
    private AddressMapper addressMapper;

    /**
     * 新增
     */
    public void add(Address address) {
        addressMapper.insert(address);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            Address address = addressMapper.selectById(id);
            if (address == null || !currentUser.getId().equals(address.getUserId())) {
                return; // 没有权限删除
            }
        }
        addressMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            deleteById(id); // 使用已经有权限检查的deleteById方法
        }
    }

    /**
     * 修改
     */
    public void updateById(Address address) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            Address existingAddress = addressMapper.selectById(address.getId());
            if (existingAddress == null || !currentUser.getId().equals(existingAddress.getUserId())) {
                return; // 没有权限修改
            }
        }
        addressMapper.updateById(address);
    }

    /**
     * 根据ID查询
     */
    public Address selectById(Integer id) {
        Account currentUser = TokenUtils.getCurrentUser();
        Address address = addressMapper.selectById(id);
        // 普通用户只能查询自己的地址
        if (RoleEnum.USER.name().equals(currentUser.getRole()) && 
            address != null && !currentUser.getId().equals(address.getUserId())) {
            return null; // 返回null表示没有权限或地址不存在
        }
        return address;
    }

    /**
     * 查询所有
     */
    public List<Address> selectAll(Address address) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            address.setUserId(currentUser.getId());
        }
        return addressMapper.selectAll(address);
    }

    /**
     * 分页查询
     */
    public PageInfo<Address> selectPage(Address address, Integer pageNum, Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            address.setUserId(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Address> list = addressMapper.selectAll(address);
        return PageInfo.of(list);
    }
}